module IPFS.Client.Command.Bootstrap (
 list,
 rm,
 add,
 rmAll,
 addDefault,
 Peers(..)
) where

import Prelude

import Data.Argonaut (class DecodeJson, decodeJson, fromString, (.:))
import Data.Either (Either)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
import Data.Maybe (Maybe(..))
import Effect.Aff (Aff)
import Foreign.Object as O
import IPFS.Client (Client)
import IPFS.Client as C
import IPFS.Client.Command (Command, defCommand)
import IPFS.Client.Utils.SendRequest (execJsonCommand)

--------------------------list------------------------
data Peers = Peers {
    peers::Array String
}

derive instance genericPeers :: Generic Peers _
instance showPeers :: Show Peers where
  show s = genericShow s

instance peersDecodeJson :: DecodeJson Peers where
  decodeJson json = do
   djson  <- decodeJson json
   peers_ <- djson .: "Peers"
   pure $ Peers {peers:peers_}

listCommand::Command
listCommand = defCommand { path = "bootstrap/list", args = Nothing ,qs = O.empty}

list::C.Client -> Aff (Either String Peers)
list client = execJsonCommand client listCommand

--------------------------rm------------------------

rmCommand::String -> Command
rmCommand hash  = defCommand { path = "bootstrap/rm", 
                               args = Just [fromString hash] ,
                               qs   = O.empty
                             }

rm::Client -> String -> Aff (Either String Peers)
rm client hash  = execJsonCommand client $ rmCommand hash

--------------------------add------------------------

addCommand::String -> Command
addCommand hash  = defCommand { path = "bootstrap/add", 
                               args = Just [fromString hash] ,
                               qs   = O.empty
                             }

add::Client -> String -> Aff (Either String Peers)
add client hash  = execJsonCommand client $ addCommand hash

--------------------------rmAll------------------------

rmAllCommand::Command
rmAllCommand = defCommand { path = "bootstrap/rm/all", args = Nothing, qs = O.empty}

rmAll::Client -> Aff (Either String Peers)
rmAll client   = execJsonCommand client  rmAllCommand

--------------------------rmAll------------------------

addDefaultCommand::Command
addDefaultCommand = defCommand { path = "bootstrap/add/default", args = Nothing, qs = O.empty}

addDefault::Client -> Aff (Either String Peers)
addDefault client  = execJsonCommand client addDefaultCommand